package com.tdogg.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tdogg.entity.Funs;
import com.tdogg.entity.GoodsType;
import com.tdogg.entity.Role;
import com.tdogg.mapper.FunsMapper;
import com.tdogg.mapper.RoleMapper;
import com.tdogg.service.IPermissionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Resource
    FunsMapper funsMapper;
    @Resource
    RoleMapper roleMapper;

    @Override
    public List<Funs> queryAllFuns() {
        return funsMapper.queryParentFuns();
    }

    @Override
    public PageInfo<Role> queryRolesBySplitePage(Integer page, Integer limit, String keyword) {
        PageHelper.startPage(page, limit);
        List<Role> data = roleMapper.queryAllRoleByKeywords(keyword);
        PageInfo<Role> info = new PageInfo<Role>(data);
        return info;
    }

    @Override
    public String addRoleWithPermission(String roleName, Integer[] perList) {
        Role r = roleMapper.selectRoleByName(roleName.trim());
        if (r != null) {
            return "已经存在该角色名称！";
        }
        Role role = new Role();
        role.setRoleName(roleName.trim());
        roleMapper.addRole(role);
        for (int i = 0; i < perList.length; i++) {
            roleMapper.addRolePermisson(role.getRoleId(), perList[i]);
        }
        return "success";
    }

    @Override
    public String updateRolePermission(Role role, Integer[] perList) {
        Role r = roleMapper.findById(role.getRoleId());
        if(r == null){
            return "角色不存在";
        }
        Role ro = roleMapper.selectNotMeRoleName(role.getRoleName(), role.getRoleId());
        if(ro != null){
            return "角色名称已存在";
        }
        roleMapper.updateRole(role);
        roleMapper.deleteRolePermission(role.getRoleId());
        for (int i = 0; i < perList.length; i++) {
            roleMapper.addRolePermisson(role.getRoleId(), perList[i]);
        }
        return "success";
    }

    @Override
    public String deleteRole(Integer roleId) {
        roleMapper.deleteRole(roleId);
        return "success";
    }

    @Override
    public List<Role> findAllRole() {
        return roleMapper.findAllRole();
    }
}
